package com.xzxy.xmlg_backend.Interceptor;

/**
 * @Author: zys
 * @CreateTime: 2025-06-20
 */


import com.xzxy.xmlg_backend.entity.Result;
import org.springframework.messaging.handler.annotation.support.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获所有 Controller 中抛出的通用异常
     *
     * @param ex       异常对象
     * @param request  请求上下文
     * @return 返回错误信息及状态码
     */
    @ExceptionHandler(Exception.class)
    public Result handleGlobalException(Exception ex, WebRequest request) {
        return Result.fail("出错了!!!"+ex.getMessage());
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    public Result handleNullPointerException(NullPointerException ex, WebRequest request) {
        Map<String, Object> errorDetails = new HashMap<>();
        errorDetails.put("timestamp", new Date());
        errorDetails.put("details", request.getDescription(false));

        return Result.fail("发生空指针异常: " + ex.getMessage());
    }

    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Result handleIllegalArgumentException(IllegalArgumentException ex, WebRequest request) {
        Map<String, Object> errorDetails = new HashMap<>();
        errorDetails.put("timestamp", new Date());
        errorDetails.put("details", request.getDescription(false));

        return Result.fail("非法参数异常: " + ex.getMessage());
    }

    /**
     * 自定义特定异常处理（例如运行时异常）
     *
     * @param ex      RuntimeException 对象
     * @param request 请求上下文
     * @return 返回错误信息及状态码
     */
    @ExceptionHandler(RuntimeException.class)
    public Result handleRuntimeException(RuntimeException ex, WebRequest request) {
        Map<String, Object> errorDetails = new HashMap<>();
        errorDetails.put("timestamp", new Date());
        errorDetails.put("details", request.getDescription(false));

        return Result.fail("运行时异常: " + ex.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, Object> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((org.springframework.validation.FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        return Result.fail("参数校验失败");
    }

}
